// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// C [author] rhyme_lph
// V [email]  rhymelph@gmail.com
// F [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_transactions_provider.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_view_provider.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_item.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:pull_to_refresh/pull_to_refresh.dart';

class DashboardTransactionsView extends StatefulWidget {
  @override
  _DashboardTransactionsViewState createState() =>
      _DashboardTransactionsViewState();
}

class _DashboardTransactionsViewState extends State<DashboardTransactionsView>
    with
        StatefulPresenter<DashboardTransactionsView, DashboardViewProvider,
            DashboardTransactionsProvider>,
        KeepAliveMixin {
  @override
  Widget buildWidget(BuildContext context) => provider.types.length == 0
      ? buildNoPermissionWidget(context)
      : SmartRefresher(
          controller: provider.refreshController,
          onRefresh: provider.onRefresh,
          onLoading: provider.onLoadMore,
          enablePullUp: provider.hasUp,
          child: ListView(
            key: PageStorageKey("Tab1"),
            physics: const ClampingScrollPhysics(),
            children: [
              _buildFilterWidget(),
              listBuilder<int>(
                selector: (_, __) => __.transactionList?.length,
                builder: (BuildContext context, int value, Widget child) =>
                    value == null
                        ? super.buildLoadingWidget(context)
                        : value == 0
                            ? super.buildEmptyWidget(provider, context)
                            : listBuilder<Map<String, List<TransactionEntity>>>(
                                selector: (_, __) =>
                                    Map.from(__.transactionMap),
                                builder: (BuildContext context,
                                        Map<String, List<TransactionEntity>>
                                            value,
                                        Widget child) =>
                                    value.isEmpty
                                        ? super
                                            .buildEmptyWidget(provider, context)
                                        : Column(
                                            children: _buildTransactionList()),
                              ),
              )
            ],
          ),
        );

  Widget _buildFilterWidget() => Padding(
        padding: EdgeInsets.only(top: getDp(20)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            buildTimeSelect(),
            PressedOpacityButton(
              onPressed: provider.onNavViewAll,
              padding: EdgeInsets.symmetric(horizontal: getDp(20)),
              child: Text(
                S.current.view_all,
                style: TextStyle(
                  color: aceBlueColor,
                  fontSize: getSp(16),
                  fontWeight: FontWeight.w700,
                  height: 14 / 16,
                ),
              ),
            )
          ],
        ),
      );

  Widget buildTimeSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectTime,
            ),
        selector: (_, __) => __.currentSelectTime);
  }

  List<Widget> _buildTransactionList() {
    List<Widget> child = [];
    for (final item in provider.transactionMap.entries) {
      child.add(TransactionRecordTitleItem(
        title: item.key,
      ));
      child.addAll(List.generate(
          item.value.length,
          (index) => listBuilder<TransactionEntity>(
                selector: (_, __) => item.value[index],
                builder:
                    (BuildContext context, TransactionEntity e, Widget child) {
                  return TransactionRecordItem(
                    onTap: () => provider.onNavTransactionDetail(e),
                    tag: TransactionTypeUtils.getTransactionType(
                        e.transactionType),
                    name: e.name ?? '',
                    currencyCode: e.currencyCode,
                    time: DateTimeUtils.formatDateTimeString(e.issuedAt),
                    amount: e.total?.toDouble(),
                    billNumber: e.number,
                    isUnpaid: e.status == 'open' && e.employeeId == null,
                    status: e.isOverdue == 1 && e.status == 'open'
                        ? "Overdue"
                        : FormUtils.getStatus(
                            TransactionTypeUtils.getTransactionTypeStatus(
                                e.transactionType),
                            e.status,
                            e.status == 'open' && e.employeeId == null ? 1 : 0),
                  );
                },
              )));
    }
    return child;
  }
}
